<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2018/1/21
 * Time: 11:49
 */

namespace App;


use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Order extends Model
{
    /**
     * 订单类型
     */
    // 购买商品
    const BUY_GOODS = 0;
    // 购买VIP
    const BUY_VIP = 1;

    // 未支付
    const NOT_PAY = 5; // 订单状态(孙泽鑫|2018-03-19|5:未支付|10:已支付(待发货)|15:已发货|20:已完成(待评价)|25:已评价)
    // 已支付
    const HAS_PAY = 10;
    // 已发货
    const HAS_DELIVER = 15;
    // 已完成
    const HAS_COMPLETE = 20;
    // 已取消
    const CANCEL_ORDER = 25;
    // 待退款
    const WAIT_REFUND = 30;
    // 已退款
    const HAS_REFUND = 35;

    // 咖啡馆status文本
    static protected $statusArray = [
        self::NOT_PAY => '未支付',
        self::HAS_PAY  => '已支付',
        self::HAS_DELIVER => '已发货',
        self::HAS_COMPLETE => '已完成',
        self::CANCEL_ORDER => '已取消',
        self::WAIT_REFUND => '待退款',
        self::HAS_REFUND => '已退款'
    ];

    static public $canRefund = [
        self::HAS_PAY,
        self::WAIT_REFUND
    ];


    // 开启软删除
    use SoftDeletes;
    // 表名称
    protected $table = 'order';
    // 开启自动时间戳
    public $timestamps = true;
    // 日期都存储为时间戳
    protected $dateFormat = 'U';

    protected $dates = [
        'pay_time',
        'created_at',
        'updated_at',
        'deleted_at',
        'expired_at',
        'refund_time'
    ];
    // 将钱数改变面额单位从元换算成分
    public function setTotalMoneyAttribute($value)
    {
        $this->attributes['total_money'] = $value*100;
    }
    // 将钱数改变面额单位从分换算成元
    public function getTotalMoneyAttribute($value)
    {
        return $value/100;
    }

    public function user()
    {
        return $this->belongsTo('App\Users', 'user_id', 'id');
    }

    public function goods()
    {
        return $this->belongsToMany('App\Goods', 'goods_mapping_order', 'order_id', 'goods_id')->withPivot(['price', 'num']);
    }

    public function getTotalCarriageAttribute()
    {
        return $this->attributes['total_carriage'] / 100;
    }

    public function setTotalCarriageAttribute($value)
    {
        $this->attributes['total_carriage'] = $value * 100;
    }

    // 追加total_goods_money字段,status的布尔类型
    public function getTotalGoodsMoneyAttribute()
    {
        return ($this->attributes['total_money'] - $this->attributes['total_carriage']) / 100;
    }

    // 追加status_text字段,status的文本类型
    public function getStatusTextAttribute()
    {
        return self::$statusArray[$this->attributes['status']];
    }

    public function getRestTimeAttribute()
    {
        return (int)(($this->attributes['expired_at'] - time()) / 60);
    }
}